package cn.xinfei.xdecision.feign;

import feign.Feign;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Cache;
import okhttp3.ConnectionPool;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.File;
import java.util.concurrent.TimeUnit;

@Data
@Slf4j
@ConditionalOnProperty(name = "xdecision.okhttp.enable")
@ConfigurationProperties(prefix = "xdecision.okhttp")  //需要有set方法
@Configuration
@ConditionalOnClass(Feign.class)
@AutoConfigureBefore(FeignAutoConfiguration.class)
public class FeignClientByOkHttp {


    private long connectTimeout;
    private long readTimeout;
    private long writeTimeout;
    private boolean retryOnConnectionFailure;
    private String cache="/tmp/cache";
    private int maxIdleConnections;
    private long keepAliveDuration;

    @Bean
    public okhttp3.OkHttpClient okHttpClient() {
        log.info("初始化okHttpClient...");
        return new okhttp3.OkHttpClient.Builder()
                //设置连接超时
                .connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
                //设置读超时
                .readTimeout(readTimeout, TimeUnit.MILLISECONDS)
                //设置写超时
                .writeTimeout(writeTimeout, TimeUnit.MILLISECONDS)
                //是否自动重连
                .retryOnConnectionFailure(retryOnConnectionFailure)
                .connectionPool(new ConnectionPool(maxIdleConnections, keepAliveDuration, TimeUnit.MINUTES))
//                .addInterceptor(new OkHttpLogInterceptor())
                .addNetworkInterceptor(new CacheInterceptor())
                .cache(new Cache(new File(cache, "okhttpcache"), 10 * 1024 * 1024))//添加缓存
                .build();
    }
}
